package com.sita.bluetactivity.MineFragment;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.sita.bluetactivity.Base.BaseActivity;
import com.sita.bluetactivity.Base.BaseApplication;
import com.sita.bluetactivity.Base.BitmapUtils;
import com.sita.bluetactivity.Base.LogUtils;
import com.sita.bluetactivity.Base.SpUtils;
import com.sita.bluetactivity.Base.ToastUtils;
import com.sita.bluetactivity.LoginAndRegister.LoginBackBean;
import com.sita.bluetactivity.R;
import com.sita.bluetactivity.http.RestClient;
import com.squareup.picasso.Picasso;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import de.hdodenhof.circleimageview.CircleImageView;
import pl.aprilapps.easyphotopicker.DefaultCallback;
import pl.aprilapps.easyphotopicker.EasyImage;
import pl.tajchert.nammu.Nammu;
import pl.tajchert.nammu.PermissionCallback;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

/**
 * Created by Jason on 2016/10/20.
 */

public class UserInfoActivity extends BaseActivity {
    private CircleImageView userImg;
    private EditText nikeName,userPhone;
    private LinearLayout allLayout;
    private LinearLayout userInfoLayout,backIcon;
    private Bitmap bitmap;
    private ImageView head_img;
    private TextView head;
    private TextView saveTx;
    private Uri imageUri;
    private File UserHeadImg;

    private ProgressDialog dialog;

    @Override
    protected void initData() {
        String urls = SpUtils.getString("UserIcon",null,BaseApplication.getContext());
        String nickName = SpUtils.getString("UserNickName",null,BaseApplication.getContext());
        String UserPhone =  SpUtils.getString("UserPhone",null,BaseApplication.getContext());
        saveTx.setText("保存");
        head.setText("个人资料");
        Picasso.with(BaseApplication.getContext()).load(urls).error(R.mipmap.head_icon).into(userImg);
        if (nickName!=null){
            nikeName.setText(nickName);
        }
        if (UserPhone!=null){
            userPhone.setText(UserPhone);
        }
  userInfoLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(Build.VERSION.SDK_INT>=23) {
            String[] mPermissionList = new String[]{Manifest.permission.CAMERA,WRITE_EXTERNAL_STORAGE};
            ActivityCompat.requestPermissions(UserInfoActivity.this, mPermissionList, 123);
        }
        showPopWindow();
    }
});
        saveTx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog = ProgressDialog.show(UserInfoActivity.this,null,"资料更新中");
                saveUserInfo();
            }
        });
    }
    //更新用户数据
    private void saveUserInfo(){
        UpUserInfoRequest request = new UpUserInfoRequest();
        request.accountId =  SpUtils.getString("AccountId",null,BaseApplication.getContext());

       String str = nikeName.getText().toString();
        if (str.length()!=0){
            request.nickName = str;
            String jsonStr = RestClient.getGson().toJson(request);
            TypedString string = new TypedString(jsonStr);

            TypedFile file = new TypedFile("User_img",positiveimgSace());
            RestClient.getRestService().upDataUserInfo(string, file, new Callback<UpDataBackBean>() {
                @Override
                public void success(UpDataBackBean upDataBackBean, Response response) {

                    if (upDataBackBean.getErrorCode().equals("0")){
                        dialog.dismiss();
                        SpUtils.putString("UserIcon",upDataBackBean.getData().getAvatar(),BaseApplication.getContext());
                        SpUtils.putString("UserNickName",upDataBackBean.getData().getNickName(),BaseApplication.getContext());
                        ToastUtils.show("数据更新成功",3000);
                    }
                }

                @Override
                public void failure(RetrofitError error) {
                    dialog.setMessage("数据更新失败");
                    dialog.dismiss();
                }
            });

        }
        else {
            ToastUtils.show("请填写完整信息",3000);
        }



    }

    private void showPopWindow() {

        final PopupWindow popupWindow = new PopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.item_popwindows, null);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);//item是否相应点击事件
        popupWindow.setOutsideTouchable(true);
        popupWindow.setContentView(view);
        popupWindow.showAtLocation(allLayout, Gravity.BOTTOM, 0, 0);
        popupWindow.update();
        Button btCam = (Button) view.findViewById(R.id.item_popupwindows_camera);
        Button btPhoto = (Button) view.findViewById(R.id.item_popupwindows_Photo);
        Button btCancle = (Button) view.findViewById(R.id.item_popupwindows_cancel);
        btCam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //进入相机
                clickTakePhoto();
                popupWindow.dismiss();
            }
        });
        btPhoto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //进入相册
                getPhone(false);
                popupWindow.dismiss();
            }
        });
        btCancle.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }
    @Override
    protected void initView() {
        userImg =  bindView(R.id.user_head_img);
        nikeName = bindView(R.id.nikeName);
        userPhone = bindView(R.id.user_phone);
        userInfoLayout = bindView(R.id.layout_userinfo);
        allLayout = bindView(R.id.all_Layout);
        head = bindView(R.id.head_tx);
        backIcon = bindView(R.id.back_layout);
        saveTx = bindView(R.id.right_tx);
       // head_img = bindView(R.id.head_logo);
        head.setVisibility(View.VISIBLE);
        backIcon.setVisibility(View.VISIBLE);
        backIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    @Override
    protected int getId() {
        return R.layout.activity_userinfo;
    }
    public static void JumpIntent(Context context){
        Intent intent = new Intent(context,UserInfoActivity.class);
        context.startActivity(intent);
    }
    private void clickTakePhoto() {
        /**Permission check only required if saving pictures to root of sdcard*/
        int permissionCheck = ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE);
        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            getPhone(true);
        } else {
            Nammu.askForPermission(this, WRITE_EXTERNAL_STORAGE, new PermissionCallback() {
                @Override
                public void permissionGranted() {
                    getPhone(true);
                }

                @Override
                public void permissionRefused() {

                }
            });
        }
    }
    private void getPhone(boolean open)   {

        if (open){
            UserHeadImg = new File(Environment.getExternalStorageDirectory(),"output_img.jpg");
            if (UserHeadImg.exists()){
                UserHeadImg.delete();
            }
            try {
                UserHeadImg.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            imageUri = Uri.fromFile(UserHeadImg);
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
            startActivityForResult(intent,1);
        }
        else {

            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            intent.putExtra("crop",true);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
            startActivityForResult(intent,2);

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bitmap bitmap = null;
        switch (requestCode){
            case 1:
                if (resultCode ==RESULT_OK){
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    intent.setDataAndType(imageUri,"image/**");
                    intent.putExtra("scale",true);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                    startActivityForResult(intent,3);
                }

                break;
            case 2:
                if (resultCode ==RESULT_OK){

                    try {
                        imageUri = data.getData();

                        bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                        userImg.setImageBitmap(bitmap);
                }


                break;
            case 3:
                if (resultCode ==RESULT_OK){

                    try {

                        bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                    userImg.setImageBitmap(bitmap);
                 //   UserHeadImg = getFilePath(imageUri);
                }
                break;


        }
    }






    //获取图片文件
    private  File  positiveimgSace(){
        String HEAD_IMG = "vehicle_head_img.jpg";

        UserHeadImg = BitmapUtils.saveBmpFile(((BitmapDrawable) userImg.getDrawable()).getBitmap(), HEAD_IMG);
        if (UserHeadImg!=null)
        {
            return UserHeadImg;
        }else {
            return null;
        }

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bitmap!=null){
            bitmap.recycle();
        }
        System.gc();
    }
}
